package com.yswl.yeeduo.ui.base;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.yswl.yeeduo.R;
import com.yswl.yeeduo.tool.KLog;

public abstract class  BaseWebViewActivity extends BaseActivity implements DownloadListener, Callback {

	protected static final String TAG = BaseWebViewActivity.class.getSimpleName();
	private static final int WEB_START = 1001;
	private static final int WEB_END = 1002;
	private static final int WEB_ERROR = 1003;
	
	
	protected WebView webView;
	private boolean mIsLanscape = false;
	private Handler mHandler;
	private RelativeLayout mLoadProgressView;
	private boolean isFirstCallWeb = false;
	public  RelativeLayout mLayout;//为了使web Desroy后移除
	private WebViewClient mWebViewClient = new WebViewClient() {

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			if (isFirstCallWeb == true) {
				super.onPageStarted(view, url, favicon);
				KLog.e(TAG, "onPageStarted=" + url);
				mHandler.sendEmptyMessage(WEB_START);
			}
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			KLog.e(TAG, "onPageFinished=" + url);
			webView.getSettings().setBlockNetworkImage(false); //使用图片加载
			mHandler.sendEmptyMessage(WEB_END);
		}
		@Override
		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			KLog.e(TAG, "onReceivedError");
			mHandler.sendEmptyMessage(WEB_ERROR);
		};

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			KLog.e(TAG, "网页链接网址-------->>" + url);
			return true;
		};
	};
	
	
	public abstract int loadView_Lanscape();

	public abstract int loadView();

	public abstract void initView();
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		
//		setContentView(R.layout.activity_webview);
		Intent __intent = getIntent();
		String __address = __intent.getStringExtra("address"); // 地址
		String __navTitle = __intent.getStringExtra("navTitle"); // 标题
		this.mIsLanscape = __intent.getBooleanExtra("isLanscape", false); // 是否 横屏
		boolean hideNavigationBar = __intent.getBooleanExtra("hideNav", false); // 隐藏标题bar 
		
		
		this.isFirstCallWeb = true;
		if (this.mIsLanscape == true) {
			super.setContentView(loadView_Lanscape());
		} else {
			super.setContentView(loadView());
		}

		this.initView();
		//是否隐藏标题bar
		if ( hideNavigationBar==true) {
			if (navigation == null) {
				navigation  = (LinearLayout)findViewById(R.id.navigation);
			}
			super.navigation.setVisibility(View.GONE);
		}
		super.mTitle.setText(__navTitle);
		this.mHandler = new Handler(this);

		this.webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);//指定滚动条样式
		this.webView.getSettings().setSupportZoom(true);// 设置允许缩放
		this.webView.getSettings().setJavaScriptEnabled(true);// 设置使用够执行JS脚本
		this.webView.getSettings().setBuiltInZoomControls(true);// 设置使支持缩放
		webView.getSettings().setBlockNetworkImage(true);//图片下载阻塞
		this.webView.getSettings().setPluginState(PluginState.ON);// 有硬件插件 无否之
//		this.webView.getSettings().setPluginsEnabled(true);// 可以使用插件
		// this.webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		// //窗体自动使用屏幕
		this.webView.getSettings().setAllowFileAccess(true); // 设置是 否 不禁用
																// webView
		this.webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);// 排版适应屏幕
		this.webView.getSettings().setUseWideViewPort(true);// 可任意比例缩放
		this.webView.getSettings().setLoadWithOverviewMode(true);// setUseWideViewPort方法设置webview推荐使用的窗口。setLoadWithOverviewMode方法是设置webview加载的页面的模式。
		this.webView.getSettings().setSavePassword(true);
		this.webView.getSettings().setSaveFormData(true);// 保存表单数据
		this.webView.getSettings().setGeolocationEnabled(true);// 启用地理定位
		this.webView.getSettings().setGeolocationDatabasePath("/data/data/org.itri.html5webview/databases/");// 设置定位的数据库路径
		this.webView.getSettings().setDomStorageEnabled(true);

		this.webView.setWebViewClient(this.mWebViewClient);
		webView.setWebChromeClient(new WebChromeClient(){
			@Override
			public void onShowCustomView(View view, CustomViewCallback callback) {
				super.onShowCustomView(view, callback);
			}
		});
		this.webView.setDownloadListener(this);
		this.webView.loadUrl(__address);
	}
	
	protected void onPause() {
		super.onPause();
		this.webView.onPause();
	}
	
	
	@Override
	protected void onResume() {
		if (this.mIsLanscape == true && getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		}
		super.onResume();
		this.webView.onResume();
	}
	
	



	@Override
	public boolean handleMessage(Message msg) {
		if (Thread.currentThread().isInterrupted() == false) {
			switch (msg.what) {
			case WEB_START:
				isFirstCallWeb = false;
				showProgressView();
				break;
			case WEB_END:
				hideProgressView();
				break;
			case WEB_ERROR:
				Toast.makeText(this, "加载网页出错", Toast.LENGTH_SHORT).show();
				break;
			}
			return true;
		}
		return false;
	}


	public void hideProgressView() {
		try {
			this.mLoadProgressView.setVisibility(View.GONE);
		} catch (Exception e) {
			e.printStackTrace();
			this.mLoadProgressView = null;
		}
	}

	public void showProgressView() {
		try {
			RelativeLayout.LayoutParams _params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
			_params.addRule(RelativeLayout.BELOW, navigation.getId());
			this.mLoadProgressView = new RelativeLayout(this);
			this.mLoadProgressView.setLayoutParams(_params);
			this.mLoadProgressView.setBackgroundColor(Color.WHITE);

			RelativeLayout.LayoutParams _progressParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			_progressParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
			ProgressBar _progressBar = new ProgressBar(this, null, android.R.attr.progressBarStyle);
			_progressBar.setLayoutParams(_progressParams);
			this.mLoadProgressView.addView(_progressBar);
			((ViewGroup) getContentView()).addView(this.mLoadProgressView);
		} catch (Exception e) {
			e.printStackTrace();
			this.mLoadProgressView = null;
		}
	}



	public View getContentView() {
		ViewGroup _window = (ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content);
		return _window.getChildAt(0);
	}



	@Override
	public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
		startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));//下载 网页端的 文件
	}
	
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
			webView.goBack(); // goBack()表示返回WebView的上一页面
			return true;
		}else if (keyCode == KeyEvent.KEYCODE_BACK) {
			this.finish();
			return true;
		}
		return false;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		//以下代码防止 webView 报错
		this.mLayout.removeView(webView);
		 webView.removeAllViews();  
		 webView.destroy();  
	}
	
	
	/**
	 * 
	 * @param context
	 * @param __address
	 * @param navTitle
	 * @param isLanscape 是否横屏
	 * @param __hideNav隐藏标题bar
	 * @return
	 */
	public static Intent createIntent(Context context, String url, String navTitle, boolean isLanscape, boolean hideNav, Class<?> cls) {
		Intent returnIntent = BaseWebViewActivity.createIntent(context, url, navTitle, isLanscape,cls);
		returnIntent.putExtra("hideNav", hideNav);
		return returnIntent;
	}
	
	public static Intent createIntent(Context context, String url, String navTitle, boolean isLanscape, Class<?> cls) {
		Intent returnIntent = new Intent();
		returnIntent.setClass(context, cls);
		returnIntent.putExtra("address", url);
		returnIntent.putExtra("navTitle", navTitle);
		returnIntent.putExtra("isLanscape", isLanscape);
		return returnIntent;
	}
	
}
